#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<windows.h>
#include<string.h>
#define high 20
#define width 60
int cells[high][width];
int cells_1[high][width]={0};
int hunter_x,hunter_y;//定义捕食者
int n;
void gotoxy(int x,int y)
{
	HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;
	pos.X=x;
	pos.Y=y;
	SetConsoleCursorPosition(handle,pos);
}
void HideCursor()
{
	CONSOLE_CURSOR_INFO cursor_info={1,0};
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cursor_info);
}
void startup()//数据初始化
{
	n=100;
	hunter_x=width/2;
	hunter_y=high/2;
	int i,j;
	for(i=0;i<high;i++)
	{
		for(j=0;j<width;j++)
		{
			cells[i][j]=1;
		}
	}
}
void show()//显示画面
{
	gotoxy(0,0);
	int i,j;
	for(i=0;i<high;i++)
	{
		for(j=0;j<width;j++)
		{
			if(cells[i][j]==1)
				printf("*");
			else if((i==hunter_y)&&(j==hunter_x))
				printf("#");//输出捕食者
			else
				printf(" ");
		}
		printf("\n");
	}
	HideCursor();
}
void updatewithoutinput()//与用户输入无关的更新
{
	int i,j;
	int tempcells[high][width];//临时储存的数组
	for(i=0;i<high;i++)
	{
		for(j=0;j<width;j++)
			tempcells[i][j]=cells[i][j];
	}
	int neibournumber=0;
	for(i=1;i<high-1;i++)
	{
		for(j=0;j<width-1;j++)
		{
			neibournumber=cells[i-1][j-1]+cells[i-1][j]+cells[i-1][j+1]+cells[i][j-1]+cells[i][j]+cells[i][j+1]+cells[i+1][j-1]+cells[i+1][j]+cells[i-1][j+1];
			if(neibournumber==3)
				tempcells[i][j]=1;
			else if(neibournumber==2)
				tempcells[i][j]=cells[i][j];
			else if((i>high/5)&&(i<high/2)&&(j>width/6)&&(j<width/3)&&(neibournumber!=0)&&(neibournumber!=8))//邻近水源更易存活
				tempcells[i][j]=1;
			else if(tempcells[i][j]==tempcells[hunter_x][hunter_y])
				tempcells[i][j]=0;//实现捕食者捕食 
			else
				tempcells[i][j]=0;//细胞的生存与否
		}
	}	
	for(i=0;i<high;i++)
	{
		for(j=0;j<width;j++)
			cells[i][j]=tempcells[i][j];
	}
	Sleep(n);
}
void updatewithinput()
{
	char input;
	if(kbhit())
	{
		input=getch();
	    if(input=='+')
		    n--;
	    if(input=='-')
		    n++;//实现速度变化
		if(input=='r')
		{
			startup();
			memcpy(cells_1,cells,sizeof(cells));
		}//重新开始
		if(input=='w')
		{
			if(hunter_y>1)
			    hunter_y--;
			else
				hunter_y=hunter_y;
		}
		if(input=='s')
		{
			if(hunter_y<high-2)
			    hunter_y++;
			else
				hunter_y=hunter_y;
		}
		if(input=='a')
		{
			if(hunter_x>1)
			    hunter_x--;
			else
				hunter_x=hunter_x;
		}
		if(input=='d')
		{
			if(hunter_x<width-2)
			    hunter_x++;
			else
				hunter_x=hunter_x;
		}//猎人的移动
		if(input==27)
		    system("pause");//增加游戏暂停功能	
		system("cls");
	}
}
int main()
{
	startup();
	while(1)
	{
		show();
		updatewithoutinput();
		updatewithinput();
	}
	return 0;
}







